import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';
import 'date_time_picker.dart';

class AddDoctorRecordDialog extends StatefulWidget {
  final String babyId;
  const AddDoctorRecordDialog({Key? key, required this.babyId})
    : super(key: key);

  @override
  State<AddDoctorRecordDialog> createState() => _AddDoctorRecordDialogState();
}

class _AddDoctorRecordDialogState extends State<AddDoctorRecordDialog> {
  final _formKey = GlobalKey<FormState>();
  DateTime _date = DateTime.now();
  final _reasonController = TextEditingController();
  final _diagnosisController = TextEditingController();
  final _prescriptionController = TextEditingController();
  final _noteController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('添加就医记录'),
      content: Form(
        key: _formKey,
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildDateTimePicker(),
              TextFormField(
                controller: _reasonController,
                decoration: const InputDecoration(labelText: '就诊原因'),
                validator: (value) => value?.isEmpty ?? true ? '请输入就诊原因' : null,
              ),
              TextFormField(
                controller: _diagnosisController,
                decoration: const InputDecoration(labelText: '诊断结果'),
                validator: (value) => value?.isEmpty ?? true ? '请输入诊断结果' : null,
              ),
              TextFormField(
                controller: _prescriptionController,
                decoration: const InputDecoration(labelText: '处方药物'),
                maxLines: 2,
              ),
              TextFormField(
                controller: _noteController,
                decoration: const InputDecoration(labelText: '备注'),
                maxLines: 2,
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(onPressed: _submit, child: const Text('保存')),
      ],
    );
  }

  Widget _buildDateTimePicker() {
    return InkWell(
      onTap: () async {
        final picked = await showDateTimePicker(
          context: context,
          initialDate: _date,
        );
        if (picked != null) {
          setState(() => _date = picked);
        }
      },
      child: InputDecorator(
        decoration: const InputDecoration(labelText: '就诊时间'),
        child: Text(DateFormat('yyyy-MM-dd HH:mm').format(_date)),
      ),
    );
  }

  void _submit() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.doctor,
          timestamp: _date,
          data: {
            'reason': _reasonController.text,
            'diagnosis': _diagnosisController.text,
            'prescription': _prescriptionController.text,
            'note': _noteController.text,
          },
        ),
      );
      if (mounted) Navigator.pop(context);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
      }
    }
  }

  @override
  void dispose() {
    _reasonController.dispose();
    _diagnosisController.dispose();
    _prescriptionController.dispose();
    _noteController.dispose();
    super.dispose();
  }
}
